package com.handler;

import com.dto.JsonResponse;
import com.exception.ConditionException;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.ClientAbortException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE) //在方法主动抛出异常时，优先由本处理器捕获
public class CommonGlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public JsonResponse<String> commonExceptionHandler(HttpServletRequest request, Exception e) {
        String errorMsg = e.getMessage();
        if (e instanceof ConditionException) {
            //如果抛出的异常是ConditionException异常，那就获取它独有的错误状态码
            String errorCode = ((ConditionException) e).getCode();
            return new JsonResponse<>(errorCode, errorMsg);
        } else {
            //如果是其他的异常类，那就使用500作为通用错误码
            return new JsonResponse<>("500", errorMsg);
        }
    }


    /**
     * 如果视频暂停一段时间会报异常CommonGlobalExceptionHandler
     * <p>
     * <p>
     * <p>
     * 如果视频播放期间突然刷新浏览器也会报异常CommonGlobalExceptionHandler，
     * 同时出现“c.i.b.s.websocket.WebSocketService: 用户连接成功, sessionId = 2, 在线连接人数为：1的日志
     */
    @ExceptionHandler(value = ClientAbortException.class)
    public void clientAbortExceptionHandler(HttpServletRequest request, Exception e) {
        String errMsg = e.getMessage();
        log.info(errMsg);
    }

}
